package com.example.datamanage.controller;

import com.example.datamanage.common.Result;
import com.example.datamanage.config.DynamicDataSource;
import com.example.datamanage.pojo.dto.DataSourceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.sql.SQLException;

/**
 * @author 28142
 * @description 数据源切换 controller
 * @date 2023/7/24 14:30
 */
@RestController
@RequestMapping("/datasource")
public class DynamicDataSourceController {
    @Autowired
    private DynamicDataSource dynamicDataSource;

    @PostMapping("/link")
    public Result link(@Valid @RequestBody DataSourceDTO dataSourceDTO) throws SQLException, NoSuchFieldException, IllegalAccessException {
        //切换数据源之前先清空
        DynamicDataSource.clearDataSource();
        System.out.println(dataSourceDTO);
        System.out.println(System.getProperty("user.dir"));
        //切换数据源
        dynamicDataSource.createDataSource(dataSourceDTO);

        System.out.println("当前数据源:"+dynamicDataSource.getConnection());

        return Result.success("当前数据源:"+dynamicDataSource.getConnection());
    }

    @PostMapping("/test")
    public Result test(@Valid @RequestBody DataSourceDTO dataSourceDTO) throws SQLException {
        System.out.println(dataSourceDTO);
        System.out.println(System.getProperty("user.dir"));
        //测试数据源
        dynamicDataSource.testDataSource(dataSourceDTO);

        System.out.println("当前数据源:"+dynamicDataSource.getConnection());

        return Result.success("连接成功"+dynamicDataSource.getConnection(), null);
    }


}
